{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dfbae8a2",
   "metadata": {},
   "source": [
    "# 所作优化\n",
    "为每个代码单元自动添加了中文“单元格概览”注释（例如“导入依赖库 / 读取数据 / 数据清洗 / 绘图 / 建模”等），方便快速跳读。\n",
    "\n",
    "为缺少 docstring 的函数补充了中文 docstring 模板（说明“功能/参数/返回值”），不改变任何执行逻辑。\n",
    "\n",
    "为常见 import 语句补充了行尾中文注释（如 numpy 数值计算、pandas 数据处理、matplotlib 绘图等）。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a310113",
   "metadata": {},
   "source": [
    "# 第一章：准备工作 (Preparation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f24e3e96",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 1: 导入依赖库 ===\n",
    "import numpy as np # 数据处理最重要的模块\n",
    "import pandas as pd # 数据处理最重要的模块\n",
    "\n",
    "from IPython.core.interactiveshell import InteractiveShell # jupyter运行输出的模块\n",
    "\n",
    "#显示每一个运行结果\n",
    "InteractiveShell.ast_node_interactivity = 'all'\n",
    "\n",
    "#设置行不限制数量\n",
    "#pd.set_option('display.max_rows',None)\n",
    "\n",
    "#设置列不限制数量\n",
    "pd.set_option('display.max_columns', None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "612d9dd7",
   "metadata": {},
   "source": [
    "# 第二章：数据导入 (Data Import)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e25c2414",
   "metadata": {},
   "source": [
    "## 常用的 Jupyter/IPython 魔法命令（速查）\n",
    "\n",
    "- 魔法命令分为两类：行魔法（以 % 开头，作用于单行）与单元魔法（以 %% 开头，作用于整个单元）。使用 `%lsmagic` 可列出当前环境可用的所有魔法，`%quickref` 查看速查帮助，任意魔法后加 `?` 可看用法说明。\n",
    "\n",
    "### 计时与性能分析\n",
    "- %time / %%time：测量单行或整个单元格的运行耗时，快速获得一次性计时结果。\n",
    "- %timeit / %%timeit：自动多次运行并给出统计（如均值、标准差），适合更可靠的微基准测试。\n",
    "- %prun：基于 cProfile 的函数级性能分析，查看不同函数的耗时构成。\n",
    "- 可选扩展：%lprun（逐行耗时，需要 line_profiler 扩展）与 %memit（内存峰值，需要 memory_profiler 扩展），需先 `%load_ext line_profiler` 或 `%load_ext memory_profiler` 才能使用。\n",
    "\n",
    "### 调试与异常\n",
    "- %debug：在异常发生后进入交互式调试器（pdb）。\n",
    "- %pdb：切换在异常发生时自动进入调试器的开关。\n",
    "- %xmode：设置异常信息的详细程度（Plain/Context/Verbose）。\n",
    "\n",
    "### 运行、导入/导出与历史\n",
    "- %run script.py：在当前内核中运行外部 Python 脚本或 Notebook 片段（支持参数）。\n",
    "- %load 路径或URL：将外部脚本或网页片段载入到当前单元格中以便编辑/运行。\n",
    "- %%writefile 文件名：把整个单元格内容写入文件（常用来快速生成脚本/配置）。\n",
    "- %history：查看输入历史，支持筛选/输出到文件等选项。\n",
    "- %save：将历史中的某些输入行保存到文件。\n",
    "\n",
    "### 变量与会话管理\n",
    "- %who / %who_ls / %whos：列出当前命名空间中的变量，`%whos` 显示更详细的类型与大小信息。\n",
    "- %reset / %xdel：清空（或选择性清理）交互命名空间、彻底删除对象并尝试释放内存。\n",
    "- %store 变量名：在不同会话之间持久化/恢复变量（轻量跨会话传递）。\n",
    "\n",
    "### 环境与系统\n",
    "- %pwd / %cd：查看或切换当前工作目录。\n",
    "- %env：查看、设置环境变量（如 `%env MY_VAR=value`）。\n",
    "- %config：查看或设置各类交互式选项（如绘图后端、显示精度等）。\n",
    "\n",
    "### 显示与可视化\n",
    "- %matplotlib inline（或 widget 等）：设置 Matplotlib 的绘图后端（inline 将图嵌入输出）。\n",
    "- %%html / %%latex / %%javascript / %%svg：直接在输出中渲染 HTML、LaTeX、JS、SVG 内容。\n",
    "- %%capture：捕获单元格的标准输出/错误输出（可赋给变量以便后续处理）。\n",
    "\n",
    "### Shell/脚本与多语言\n",
    "- %%bash / %%sh / %%script：在整个单元格中以指定脚本语言运行（最常用的是 bash/sh）。\n",
    "\n",
    "### 扩展与生态\n",
    "- %load_ext / %unload_ext / %reload_ext：加载、卸载或重载 IPython 扩展，许多第三方扩展会提供额外的魔法命令（如上面的 line_profiler/memory_profiler）。\n",
    "\n",
    "提示：不同内核或环境中可用的魔法可能略有差异，先用 `%lsmagic` 检查你当前会话支持的命令集合。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be217c07",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8401985d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 2: 读取数据、数据清洗/转换 ===\n",
    "%%time\n",
    "data = pd.read_csv('datasets/000001.csv')\n",
    "data['Day'] = pd.to_datetime(data['Day'],format='%Y/%m/%d')\n",
    "data.set_index('Day', inplace = True)\n",
    "data.sort_values(by = ['Day'],axis=0, ascending=True)\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f177a0b7",
   "metadata": {},
   "source": [
    "# 第三章：收益率计算基础 (Return Calculation Basics)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f99bab7",
   "metadata": {},
   "source": [
    "股票的收益率的计算一般使用的是 **收盘价** 来计算。\n",
    "\n",
    "\n",
    "* Raw Return: $R_t = \\frac{p_t - p_{t-1}}{p_{t-1}} $\n",
    "* Log Return: $r_t = log(p_t) - log(p_{t-1})$\n",
    "\n",
    "自然对数收益率与原始收益率的关系：\n",
    "\n",
    "$r_t = log(1 + R_t)$\n",
    "\n",
    "* 在实际数据中，我们常用收盘价来计算收益率。为什么？\n",
    "* 对数收益率和原始收益率的区别在哪里？分别用在什么样的场景呢？"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b00f7708",
   "metadata": {},
   "source": [
    "## 复利的计算\n",
    "设某资产的的初始值为 $C$, 名义上的年利率为 $r$ ， 但是在一年内分成 $m$ 次付息，理论上每次付息 $C \\frac{r}{m}$, 最终的资产净值应为 \n",
    "\n",
    "$C+C \\frac{r}{m} \\times m=C(1+r)$; \n",
    "\n",
    "但是，因为提前付息，所以提前支付的利息也进入账户增值，从第二次付息开始，支付的利息就超过了 $C \\frac{r}{m}$, 使得一年后的净值要高于 $C(1+r)$。 一年后的净值为\n",
    "\n",
    "$C\\left(1+\\frac{r}{m}\\right)^{m}$\n",
    "\n",
    "当 $m \\rightarrow \\infty$ 时，由极限 $\\lim _{x \\rightarrow+\\infty}\\left(1+\\frac{1}{x}\\right)^{x}=e$, 可知\n",
    "\n",
    "$\\lim _{m \\rightarrow \\infty} C\\left(1+\\frac{r}{m}\\right)^{m}=\\lim _{m \\rightarrow \\infty} C\\left[\\left(1+\\frac{r}{m}\\right)^{\\frac{m}{r}}\\right]^{r}=C e^{r}$\n",
    "\n",
    "这时 $r$ 称为连续复利， 它也对应某个时间单位（一般是年)， $R=e^{r}-1$ 是连续复利 $r$ 对应的实际利率, $r$ 与 $R$ 的关系为\n",
    "\n",
    "$R=e^{r}-1, \\quad r=\\ln (1+R)$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3b2a6c9",
   "metadata": {},
   "source": [
    "# 第四章：日度收益率计算 (Daily Return Calculation)\n",
    "\n",
    "## 4.1 数据准备\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "819405f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 3: 通用计算/执行 ===\n",
    "data_new = data['1995-01':'2025-08'].copy()\n",
    "data_new['Close'] = pd.to_numeric(data_new['Close'])\n",
    "data_new['Preclose'] = pd.to_numeric(data_new['Preclose'])\n",
    "data_new"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15995f78",
   "metadata": {},
   "source": [
    "## 4.2 多种日度收益率计算方法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efd1f9fb",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 4: 通用计算/执行 ===\n",
    "# 计算000001上证指数日收益率 - 方法1：直接使用向量化操作（最推荐的方式）\n",
    "data_new['Raw_return'] = data_new['Close'] / data_new['Preclose'] - 1\n",
    "data_new['Log_return'] = np.log(data_new['Close']) - np.log(data_new['Preclose'])\n",
    "\n",
    "# 方法2：使用pandas的pct_change函数计算收益率（适用于时间序列数据）\n",
    "# 注意：这种方法需要数据已经按时间排序\n",
    "data_new['Pct_change_return'] = data_new['Close'].pct_change()\n",
    "\n",
    "# 方法3：使用apply方法（不推荐，因为速度较慢）\n",
    "data_new['Apply_return'] = data_new.apply(lambda row: row['Close'] / row['Preclose'] - 1, axis=1)\n",
    "\n",
    "# 方法4：使用diff和div方法组合（另一种向量化操作）\n",
    "data_new['Diff_div_return'] = data_new['Close'].diff() / data_new['Close'].shift(1)\n",
    "\n",
    "# 比较不同方法计算结果的差异\n",
    "data_new"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9742685",
   "metadata": {},
   "source": [
    "## 4.3 循环与向量化方法比较\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3edbe25",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "* 注意下面代码的运行，Python靠缩进来判断代码的级别，注意使用。\n",
    "* 能不用for while等循环就少用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3b042bf",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 5: 循环/迭代 ===\n",
    "# 方法5：使用for循环计算收益率（不推荐，效率低）\n",
    "# 这种方法在大数据集上会非常慢，仅作为教学示例\n",
    "\n",
    "# 创建新列存储结果\n",
    "if 'Loop_return' not in data_new.columns:\n",
    "    data_new['Loop_return'] = np.nan\n",
    "\n",
    "# 使用for循环计算\n",
    "for i in range(len(data_new)):\n",
    "    data_new.iloc[i, data_new.columns.get_loc('Loop_return')] = data_new.iloc[i, data_new.columns.get_loc('Close')] / data_new.iloc[i, data_new.columns.get_loc('Preclose')] - 1\n",
    "\n",
    "# 方法6：使用zip和enumerate组合（比纯for循环更Pythonic）\n",
    "close_values = data_new['Close'].values\n",
    "preclose_values = data_new['Preclose'].values\n",
    "loop_return_values = []\n",
    "\n",
    "for i, (close, preclose) in enumerate(zip(close_values, preclose_values)):\n",
    "    if preclose != 0 and not np.isnan(preclose):\n",
    "        loop_return_values.append(close / preclose - 1)\n",
    "    else:\n",
    "        loop_return_values.append(np.nan)\n",
    "\n",
    "data_new['Loop_return2'] = loop_return_values\n",
    "\n",
    "# 方法7：使用numpy的向量化操作（高效且简洁）\n",
    "data_new['Numpy_return'] = (data_new['Close'].values / data_new['Preclose'].values) - 1\n",
    "\n",
    "# 显示结果\n",
    "data_new"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abfe4128",
   "metadata": {},
   "source": [
    "# 第五章 月度收益\n",
    "\n",
    "## 5.1 月度收益率计算\n",
    "\n",
    "月度收益率是金融分析中最常用的周期性收益率之一。$t$ 月的收益率使用该月月末的收盘价和上个月$t-1$月末的收盘价来计算：\n",
    "\n",
    "* 原始收益率 (Raw Return): $R_t = \\frac{p_t - p_{t-1}}{p_{t-1}} $\n",
    "* 对数收益率 (Log Return): $r_t = log(p_t) - log(p_{t-1})$\n",
    "\n",
    "下面我们将介绍多种计算月度收益率的方法。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bec974d",
   "metadata": {},
   "source": [
    "### resample方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d404a2c1",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 6: 通用计算/执行 ===\n",
    "# 方法1：使用resample函数计算月度对数收益率并转换为原始收益率\n",
    "# 这种方法适合对数收益率，因为对数收益率可以直接相加\n",
    "Month_data1 = data_new.resample('ME')['Log_return'].sum().to_frame(name='Log_return') \n",
    "Month_data1['Raw_Return'] = np.exp(Month_data1['Log_return']) - 1\n",
    "\n",
    "# 添加年月信息便于分析\n",
    "Month_data1['Year'] = Month_data1.index.year\n",
    "Month_data1['Month'] = Month_data1.index.month\n",
    "\n",
    "# 显示结果\n",
    "Month_data1.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e69abe4e",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 7: 通用计算/执行 ===\n",
    "# 方法2：使用resample取月末价格计算月度收益率\n",
    "# 这种方法直接使用月末价格计算收益率，更符合金融实践\n",
    "Month_data2 = data_new.resample('ME')['Close'].last().to_frame()\n",
    "Month_data2['Preclose'] = Month_data2['Close'].shift(1)\n",
    "Month_data2['Raw_return'] = Month_data2['Close'] / Month_data2['Preclose'] - 1\n",
    "Month_data2['Log_return'] = np.log(Month_data2['Close']) - np.log(Month_data2['Preclose'])\n",
    "\n",
    "# 添加年月信息\n",
    "Month_data2['Year'] = Month_data2.index.year\n",
    "Month_data2['Month'] = Month_data2.index.month\n",
    "\n",
    "# 显示结果\n",
    "Month_data2.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0c0b1ed",
   "metadata": {},
   "source": [
    "### groupy by 方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "476c562e",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 8: 通用计算/执行 ===\n",
    "# “1990-12-12”日期格式 里面的year年份 month月份 day 直接提出取来\n",
    "data_new2 = data_new.copy()\n",
    "data_new2['year'] = data_new2.index.year\n",
    "data_new2['month'] = data_new2.index.month\n",
    "data_new2\n",
    "# 使用的时间、日期格式提取 字符串提出的方式 前四个字符当作年份 6-7字符是月份 提取出来的是字符串 变成数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0205c0f",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 9: 数据清洗/转换 ===\n",
    "# 方法3：使用groupby函数按年月分组计算月度收益率\n",
    "# 首先提取年月信息\n",
    "data_new3 = data_new.copy()\n",
    "data_new3['year'] = data_new3.index.year\n",
    "data_new3['month'] = data_new3.index.month\n",
    "\n",
    "# 使用groupby按年月分组，然后对每组的对数收益率求和\n",
    "Month_data3 = data_new3.groupby(['year', 'month'])['Log_return'].sum().to_frame()\n",
    "Month_data3['Raw_Return'] = np.exp(Month_data3['Log_return']) - 1\n",
    "\n",
    "# 显示结果\n",
    "Month_data3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f165688",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# === 单元格 10: 数据清洗/转换 ===\n",
    "# 方法4：使用apply和lambda函数进行更灵活的分组计算\n",
    "# 这种方法可以对每个月的数据进行更复杂的操作\n",
    "Month_data4 = pd.DataFrame(\n",
    "    data_new3.groupby(['year', 'month'])['Log_return'].apply(lambda x: sum(x)))\n",
    "Month_data4.columns = ['Log_return']\n",
    "Month_data4['Raw_Return'] = np.exp(Month_data4['Log_return']) - 1\n",
    "\n",
    "# 方法5：使用agg函数同时计算多个统计量\n",
    "Month_data5 = data_new3.groupby(['year', 'month']).agg({\n",
    "    'Log_return': ['sum', 'mean', 'std', 'count'],\n",
    "    'Raw_return': ['mean', 'std']\n",
    "})\n",
    "\n",
    "# 显示结果\n",
    "print(\"方法4结果:\")\n",
    "print(Month_data4.head())\n",
    "print(\"\\n方法5结果 (包含多个统计量):\")\n",
    "print(Month_data5.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "720a014b",
   "metadata": {},
   "source": [
    "# 第六章 季度收益"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "373dc625",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 11: 通用计算/执行 ===\n",
    "# 计算季度收益率\n",
    "# 方法1：使用resample函数的'QE'参数（季度末）\n",
    "Quarter_data1 = data_new.resample('QE')['Log_return'].sum().to_frame(name='Log_return')\n",
    "Quarter_data1['Raw_Return'] = np.exp(Quarter_data1['Log_return']) - 1\n",
    "Quarter_data1['Year'] = Quarter_data1.index.year\n",
    "Quarter_data1['Quarter'] = Quarter_data1.index.quarter\n",
    "\n",
    "# 方法2：使用季度末价格计算\n",
    "Quarter_data2 = data_new.resample('QE')['Close'].last().to_frame()\n",
    "Quarter_data2['Preclose'] = Quarter_data2['Close'].shift(1)\n",
    "Quarter_data2['Raw_return'] = Quarter_data2['Close'] / Quarter_data2['Preclose'] - 1\n",
    "Quarter_data2['Log_return'] = np.log(Quarter_data2['Close']) - np.log(Quarter_data2['Preclose'])\n",
    "\n",
    "# 显示结果\n",
    "print(\"季度对数收益率汇总:\")\n",
    "Quarter_data1\n",
    "print(\"\\n季度末价格计算的收益率:\")\n",
    "Quarter_data2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7ceb752",
   "metadata": {},
   "source": [
    "# 第七章 年度收益"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdad792c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 12: 数据清洗/转换 ===\n",
    "# 计算年度收益率\n",
    "# 方法1：使用resample函数的'YE'参数（年末）\n",
    "Year_data1 = data_new.resample('YE')['Log_return'].sum().to_frame(name='Log_return')\n",
    "Year_data1['Raw_Return'] = np.exp(Year_data1['Log_return']) - 1\n",
    "\n",
    "# 方法2：使用年末价格计算\n",
    "Year_data2 = data_new.resample('YE')['Close'].last().to_frame()\n",
    "Year_data2['Preclose'] = Year_data2['Close'].shift(1)\n",
    "Year_data2['Raw_return'] = Year_data2['Close'] / Year_data2['Preclose'] - 1\n",
    "Year_data2['Log_return'] = np.log(Year_data2['Close']) - np.log(Year_data2['Preclose'])\n",
    "\n",
    "# 方法3：使用groupby按年分组\n",
    "data_new4 = data_new.copy()\n",
    "data_new4['year'] = data_new4.index.year\n",
    "Year_data3 = data_new4.groupby('year')['Log_return'].sum().to_frame()\n",
    "Year_data3['Raw_Return'] = np.exp(Year_data3['Log_return']) - 1\n",
    "\n",
    "# 显示结果\n",
    "print(\"年度对数收益率汇总:\")\n",
    "Year_data1\n",
    "print(\"\\n年末价格计算的收益率:\")\n",
    "Year_data2\n",
    "print(\"\\n使用groupby计算的年度收益率:\")\n",
    "Year_data3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dce51999",
   "metadata": {},
   "source": [
    "# 第八章 计算滚动收益率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27edaf42",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 13: 循环/迭代 ===\n",
    "# 计算滚动收益率（例如：过去30天、60天、90天的收益率 注意这里指的是前30个观测值）\n",
    "# 这在金融分析中非常常见，用于观察不同时间窗口的收益表现\n",
    "\n",
    "# 方法1：使用rolling窗口函数计算滚动对数收益率之和\n",
    "rolling_returns = pd.DataFrame()\n",
    "for window in [5, 10, 20, 30, 60]:\n",
    "    # 计算滚动窗口的对数收益率之和\n",
    "    rolling_log_return = data_new['Log_return'].rolling(window=window).sum()\n",
    "    # 转换为原始收益率\n",
    "    rolling_returns[f'Rolling_{window}d_Return'] = np.exp(rolling_log_return) - 1\n",
    "\n",
    "# 方法2：使用pct_change计算滚动价格变化\n",
    "rolling_price_returns = pd.DataFrame()\n",
    "for window in [5, 10, 20, 30, 60]:\n",
    "    rolling_price_returns[f'Rolling_{window}d_Price_Return'] = data_new['Close'].pct_change(periods=window)\n",
    "\n",
    "# 显示结果\n",
    "print(\"滚动收益率 (基于对数收益率累加):\")\n",
    "print(rolling_returns.tail())\n",
    "print(\"\\n滚动收益率 (基于价格变化):\")\n",
    "print(rolling_price_returns.tail())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7495dc3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 14: 通用计算/执行 ===\n",
    "# 计算累积收益率\n",
    "# 累积收益率用于观察长期投资表现，从某个起始点开始累积\n",
    "\n",
    "# 方法1：使用对数收益率累加后转换\n",
    "# 这是最准确的方法，特别是对于长期累积\n",
    "cumulative_returns = pd.DataFrame()\n",
    "cumulative_returns['Cumulative_Log_Return'] = data_new['Log_return'].cumsum()\n",
    "cumulative_returns['Cumulative_Return'] = np.exp(cumulative_returns['Cumulative_Log_Return']) - 1\n",
    "\n",
    "# 方法2：使用cumprod函数直接累乘(1+r)\n",
    "# 这种方法在金融实践中也很常见\n",
    "cumulative_returns['Cumulative_Return_Prod'] = (1 + data_new['Raw_return']).cumprod() - 1\n",
    "\n",
    "# 方法3：使用pandas的累积函数\n",
    "cumulative_returns['Cumulative_Return_Alt'] = data_new['Raw_return'].add(1).cumprod().sub(1)\n",
    "\n",
    "# 显示结果\n",
    "print(\"不同方法计算的累积收益率:\")\n",
    "cumulative_returns"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08618c1a",
   "metadata": {},
   "source": [
    "# 收益率计算方法总结\n",
    "\n",
    "## 日度收益率计算方法\n",
    "1. **原始收益率 (Raw Return)**\n",
    "   - 公式：$R_t = \\frac{p_t - p_{t-1}}{p_{t-1}} = \\frac{p_t}{p_{t-1}} - 1$\n",
    "   - 实现方法：\n",
    "     - 向量化操作：`data['Raw_return'] = data['Close'] / data['Preclose'] - 1`\n",
    "     - pct_change函数：`data['Close'].pct_change()`\n",
    "     - diff和div组合：`data['Close'].diff() / data['Close'].shift(1)`\n",
    "\n",
    "2. **对数收益率 (Log Return)**\n",
    "   - 公式：$r_t = \\ln(p_t) - \\ln(p_{t-1}) = \\ln(\\frac{p_t}{p_{t-1}}) = \\ln(1 + R_t)$\n",
    "   - 实现方法：`data['Log_return'] = np.log(data['Close']) - np.log(data['Preclose'])`\n",
    "\n",
    "## 不同周期收益率计算方法\n",
    "1. **月度/季度/年度收益率**\n",
    "   - 对数收益率累加法：`data.resample('ME')['Log_return'].sum()`\n",
    "   - 期末价格法：`data.resample('ME')['Close'].last().pct_change()`\n",
    "   - 分组汇总法：`data.groupby(['year', 'month'])['Log_return'].sum()`\n",
    "\n",
    "2. **滚动收益率**\n",
    "   - 对数收益率累加：`data['Log_return'].rolling(window=30).sum()`\n",
    "   - 价格变化法：`data['Close'].pct_change(periods=30)`\n",
    "\n",
    "3. **累积收益率**\n",
    "   - 对数收益率累加：`np.exp(data['Log_return'].cumsum()) - 1`\n",
    "   - 连乘法：`(1 + data['Raw_return']).cumprod() - 1`\n",
    "\n",
    "## 年化收益率计算方法\n",
    "1. **对数收益率年化**：`np.exp(total_log_return / total_years) - 1`\n",
    "2. **累积收益率年化**：`(1 + total_return) ** (1 / total_years) - 1`\n",
    "3. **几何平均年化**：`daily_return_factor ** 252 - 1`\n",
    "\n",
    "## 原始收益率与对数收益率的区别\n",
    "1. **累加性**：对数收益率可以直接累加，原始收益率需要连乘\n",
    "2. **对称性**：对数收益率在正负方向上更对称\n",
    "3. **适用场景**：\n",
    "   - 对数收益率适合长期分析和理论研究\n",
    "   - 原始收益率更直观，适合短期分析和实际应用"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
